package middleware

import (
	"fmt"
	"gitee.com/git_public/vfaith/fount/handle"
	"gitee.com/git_public/vfaith/sugar"
	"log"
	"net/http"
)

func initPrimaryHandler(w http.ResponseWriter, r *http.Request) *handle.PrimaryHandler {
	id, _ := sugar.ToInteger(r.FormValue("id"))
	if id == 0 {
		http.Error(w, "Internal Server Error：【参数为空】", http.StatusBadRequest)
		return nil
	}

	return &handle.PrimaryHandler{
		BlendHttp: handle.NewBlendHttp(w, r),
		Id:        id,
	}

}

func HttpContextPrimary(next func(handler *handle.PrimaryHandler) error) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		primaryHandler := initPrimaryHandler(w, r)
		if primaryHandler == nil {
			return
		}

		err := next(primaryHandler)
		if err != nil {
			log.Print(err)
			http.Error(w, fmt.Sprintf("Internal Server Error：【%s】", err), http.StatusInternalServerError)
		}
	}
}

func HttpContextPrimaryNoError(next func(handler *handle.PrimaryHandler)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		primaryHandler := initPrimaryHandler(w, r)
		if primaryHandler == nil {
			return
		}

		next(primaryHandler)
	}
}
